<template>
  <div class="setlunbo">
    <div class="subhead">
      <p>
        客户端显示的轮播图。最多5张，请上传jpg, png格式的图片。建议图片尺寸为 750×300px，建议图片大小不超过2MB。
        <el-button type="text" class="subhead-tip">如何制作合适的图片</el-button>
        <el-button type="primary" style="float:right" @click="saveInfo">提交</el-button>
      </p>
    </div>
    <template v-for="(item,index) in data">
      <el-row
        :gutter="10"
        :key="index"
        type="flex"
        justify="start"
        style="width:100%;padding-top:20px;"
      >
        <el-col :span="3">
          <span style="float:right;">轮播图{{ index+1 }}</span>
        </el-col>
        <el-col :span="7">
          <img v-if="item.fileUrl" :src="item.fileUrl" alt class="img">
          <el-upload
            :on-change="(file,fileList) => handleChange(file,fileList,item) "
            :http-request="() => upLoadFile(item)"
            :limit="1"
            action
            class="upload-demo"
            accept="image/jpeg,image/png,image/jpg"
          >
            <el-button slot="trigger" size="small" type="primary">上传</el-button>
            <el-button
              v-if="item.fileId"
              style="margin-left: 10px;"
              size="small"
              type="danger"
              @click="deleteById(item)"
            >删除
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，建议图片尺寸为 750×300px，且不超过500kb</div>
          </el-upload>
        </el-col>
        <el-col v-if="item.fileId" :span="14">
          <el-radio-group v-model="item.noOperation">
            <el-radio label="1" border>默认(无触发动作)</el-radio>
            <el-radio label="2" border>跳转到链接地址</el-radio>
            <el-radio label="3" border>跳转到内部课程</el-radio>
          </el-radio-group>
          <div style="margin-top:20px;width:493px;">
            <el-input
              v-if="item.noOperation === '2'"
              v-model="item.url"
              placeholder="http://"
              @blur="handleBlur(item)"
            />
            <span style="color: red">&nbsp;&nbsp;{{ item.checkMssage }}</span>
          </div>
          <div v-if="item.noOperation === '3'">
            <el-button
              type="primary"
              size="medium"
              style="float:left;"
              @click="selectCourse(item.num)"
            >选课
            </el-button>
            <div class="grid-body">
              <img :src="item.pictureUrl ? item.pictureUrl : noSelect" alt class="img">
              <span v-if="!item.pictureUrl" class="title">还没有选择课程</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <course-dialog
      :dialog="dialog"
      :dialog-data="dialogData"
      @changeVisiable="changeVisiable"
      @handleClickSelect="handleClickSelect"
    />
  </div>
</template>

<script>
  import courseDialog from './dialog'
  import {deleteRotation, getCourseList, getRotations, saveRotation} from '@/api/operate/mbcontent' // 数据接口
  import {upLoadFile, upLoadFile_oss} from '@/api/upLoadFile' // 数据接口
  import {getTenantId, getUserId} from '@/utils/auth'

  export default {
    components: {
      courseDialog
    },
    data() {
      return {
        reg: /^((https|http|ftp|rtsp|mms){0,1}(:\/\/){0,1})(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/,
        fileList: [],
        imageUrl: '',
        noSelect: '/src/views/operate/components/mbcontent/noSelect.png',
        dialog: false,
        dialogData: {
          search: '',
          num: '',
          currentpage: 1,
          pagesize: 5,
          subject: [],
          listFilter: []
        },
        data: [
          {
            id: '',
            num: '0',
            fileId: '',
            fileUrl: '',
            noOperation: '1',
            url: '',
            courseId: '',
            courseTitle: '',
            pictureUrl: '',
            checkMssage: '',
            file: ''
          },
          {
            id: '',
            num: '1',
            fileId: '',
            fileUrl: '',
            noOperation: '1',
            url: '',
            courseId: '',
            courseTitle: '',
            pictureUrl: '',
            checkMssage: '',
            file: ''
          },
          {
            id: '',
            num: '2',
            fileId: '',
            fileUrl: '',
            noOperation: '1',
            url: '',
            courseId: '',
            courseTitle: '',
            pictureUrl: '',
            checkMssage: '',
            file: ''
          },
          {
            id: '',
            num: '3',
            fileId: '',
            fileUrl: '',
            noOperation: '1',
            url: '',
            courseId: '',
            courseTitle: '',
            pictureUrl: '',
            checkMssage: '',
            file: ''
          },
          {
            id: '',
            num: '4',
            fileId: '',
            fileUrl: '',
            noOperation: '1',
            url: '',
            courseId: '',
            courseTitle: '',
            pictureUrl: '',
            checkMssage: '',
            file: ''
          }
        ],
        saveData: []
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      handleBlur(item) {
        if (!this.reg.test(item.url)) {
          item.checkMssage = '输入的值并不是一个合法的网址，请重新输入！'
        } else {
          item.checkMssage = ''
        }
      },
      getData() {
        getRotations(getTenantId()).then(response => {
          response.data.items.forEach((item) => {
            this.data[item.num].id = item.id
            this.data[item.num].num = item.num
            this.data[item.num].fileId = item.fileId
            this.data[item.num].fileUrl = item.fileUrl
            this.data[item.num].noOperation = item.noOperation.toString()
            this.data[item.num].url = item.url
            this.data[item.num].courseId = item.courseId
            this.data[item.num].courseTitle = item.courseTitle
            this.data[item.num].pictureUrl = item.pictureUrl
          })
        })
      },
      selectCourse(num) {
        const params = {}
        params.page = this.dialogData.currentpage
        params.pageSize = this.dialogData.pagesize
        params.name = this.dialogData.search
        params.tenantId = getTenantId()
        getCourseList(params).then(response => {
          this.dialogData.subject = response.data.items
          this.dialogData.listFilter = response.data.items
          this.dialogData.num = num
        })
        this.dialog = true
      },
      changeVisiable(val) {
        this.dialog = val
      },
      handleClickSelect(item, num) {
        this.data[num].courseId = item.id
        this.data[num].courseTitle = item.title
        this.data[num].pictureUrl = item.middlePicture
        this.dialog = false
      },
      handleChange(file, fileList, item) {
        item.file = file.raw
      },
      upLoadFile(item) {
        const form = new FormData()
        form.append('name', item.file.name)
        form.append('file', item.file)
        form.append('tenantId', getTenantId())
        let type = item.file.name.substring(item.file.name.lastIndexOf('.') + 1)
        form.append('type', type)
        upLoadFile_oss(form).then(response => {
          this.data[item.num].fileUrl = response.data.url
          this.data[item.num].fileId = response.data.id
        })
      },
      saveInfo() {
        this.data.map(item => {
          item.userId = getUserId()
          item.tenantId = getTenantId()
          if (item.fileId) {
            this.saveData.push(item)
          }
        })
        saveRotation(this.saveData).then(() => {
          this.$notify({
            title: '成功',
            message: '提交成功！',
            type: 'success',
            duration: 2000
          })
        })
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      deleteById(item) {
        this.$confirm('确认要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (item.id) {
            deleteRotation(item.id).then(response => {
              this.$notify({
                title: '成功',
                message: '删除成功！',
                type: 'success',
                duration: 2000
              })
              this.initData()
            })
          } else {
            item.fileId = ''
            item.fileUrl = ''
            this.fileList = []
            this.$notify({
              title: '成功',
              message: '删除成功！',
              type: 'success',
              duration: 2000
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
      },
      initData() {
        this.data.map((item, index) => {
          item.id = ''
          item.num = index
          item.fileId = ''
          item.fileUrl = ''
          item.noOperation = '1'
          item.url = ''
          item.courseId = ''
          item.courseTitle = ''
          item.pictureUrl = ''
        })
        this.getData()
      }
    }
  }
</script>

<style lang="scss">
  .setlunbo {
    .subhead {
      background-color: #f8f8f8;
      width: 100%;
      height: 38px;
      line-height: 38px;
      font-size: 14px;
      @media screen and (max-width: 1300px) {
        font-size: 12px;
      }

      .subhead-tip {
        @media screen and (max-width: 1300px) {
          font-size: 12px;
        }
      }

      p {
        margin: 0;
        box-sizing: border-box;
        padding-left: 20px;
        padding-right: 20px;
      }

      .submmit {
        float: right;
      }
    }

    .el-row {
      .img {
        width: 100%;
      }
    }

    .grid-body {
      position: relative;
      width: 170px;
      display: block;
      border-radius: 4px;
      color: #353535;
      float: left;
      margin-left: 10px;
      margin-top: 0;

      .img {
        width: 100%;
        height: auto;
      }

      .title {
        display: block;
        padding: 10px;
        min-height: 52px;
        color: #555;
        font-weight: bold;
      }
    }
  }
</style>
